package com.yhw.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yhw.common.exception.Assert;
import com.yhw.common.result.ResponseEnum;
import com.yhw.srb.core.enums.UserBindEnum;
import com.yhw.srb.core.hfb.FormHelper;
import com.yhw.srb.core.hfb.HfbConst;
import com.yhw.srb.core.hfb.RequestHelper;
import com.yhw.srb.core.mapper.UserInfoMapper;
import com.yhw.srb.core.pojo.entity.UserBind;
import com.yhw.srb.core.mapper.UserBindMapper;
import com.yhw.srb.core.pojo.entity.UserInfo;
import com.yhw.srb.core.pojo.vo.UserBindVO;
import com.yhw.srb.core.service.UserBindService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author yhw
 * @since 2022-08-29
 */
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public String commitBindUser(UserBindVO userBindVO, Long userId) {

        //查询身份证号码是否绑定    不允许另一个账号也用这个身份证绑卡
        String idCard = userBindVO.getIdCard();
        LambdaQueryWrapper<UserBind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBind::getIdCard,idCard)
                    .ne(UserBind::getUserId,userId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);
        //USER_BIND_IDCARD_EXIST_ERROR(-301, "身份证号码已绑定")
        Assert.isNull(userBind, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);

        //查询用户绑定信息
        LambdaQueryWrapper<UserBind> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(UserBind::getUserId,userId);
        userBind = baseMapper.selectOne(queryWrapper1);

        //判断是否有绑定记录
        if (userBind == null){
            //如果未创建绑定记录，则创建一条记录
            userBind = new UserBind();
            BeanUtils.copyProperties(userBindVO,userBind);
            userBind.setUserId(userId);
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            baseMapper.insert(userBind);
        }else {
            //曾经跳转到托管平台，但是未操作完成，此时将用户最新填写的数据同步到userBind对象
            // 就是这个commitBindUser方法执行完 返回form表单(自动提交) 已经跳转到hfb那边了 但是没有设置支付密码等操作 就退出不绑定了，hfb那边并没有记录，此时又来绑定
            BeanUtils.copyProperties(userBindVO,userBind);
            baseMapper.updateById(userBind);
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId",HfbConst.AGENT_ID);   // HfbConst.AGENT_ID   hfb给商户分配的唯一标识
        paramMap.put("agentUserId", userId);
        paramMap.put("idCard",userBindVO.getIdCard());
        paramMap.put("personalName", userBindVO.getName());
        paramMap.put("bankType", userBindVO.getBankType());
        paramMap.put("bankNo", userBindVO.getBankNo());
        paramMap.put("mobile", userBindVO.getMobile());
        paramMap.put("returnUrl", HfbConst.USERBIND_RETURN_URL);   // HfbConst.USERBIND_RETURN_URL   就是绑定完成后 点“返回”的 目标地址
        paramMap.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);   // HfbConst.USERBIND_NOTIFY_URL   就是绑定完成后 hfb 会向 srb 的这个url 发请求
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        //  构建充值自动提交表单
        //  HfbConst.USERBIND_URL  用户绑定汇付宝平台url地址
        //  paramMap               汇付宝平台 要求的参数
        String formStr = FormHelper.buildForm(HfbConst.USERBIND_URL, paramMap);

        return formStr;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notify(Map<String, Object> paramMap) {

        String bindCode = (String)paramMap.get("bindCode");
        String userId = (String)paramMap.get("agentUserId");

        //根据user_id查询user_bind记录
        LambdaQueryWrapper<UserBind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBind::getUserId,userId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);

        //更新用户绑定表
        userBind.setBindCode(bindCode);
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        baseMapper.updateById(userBind);

        //更新用户信息表
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Long.parseLong(userId));
        userInfo.setBindCode(bindCode);
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
        userInfo.setName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());

        userInfoMapper.updateById(userInfo);

    }

    @Override
    public String getBindCodeByUserId(Long userId) {

        LambdaQueryWrapper<UserBind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBind::getUserId, userId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);
        String bindCode = userBind.getBindCode();
        return bindCode;

    }
}
